/**
 * 错误处理中间件
 */

import { ContextProp } from "../appTypes";
import log from "../utils/log";


export const ctxRes = async(ctx:ContextProp,next:any)=>{
  try {
    ctx.error = (code: number, msg: string) => {
      if (code === 500) {
        ctx.status = 500;
      }
      ctx.response.body = { code, msg };
    };
    ctx.success = (data: any, msg?: string) => {
      ctx.response.body = {
        code: 200,
        msg: msg || "success",
        data: data || {},
      };
    };
    await next();
  } catch (e: any) {
    log.error(e);
    ctx.status = 500;
    ctx.response.body = { code: 500, msg: "System Error" };
  }
}